using homework_2_test_first_development.Models;

namespace homework_2_test_first_development.Services;

internal static class BarcodeProcessor
{
    public static char Seperator => '-';

    public static IEnumerable<OrderItem> ParseBarcodes(IEnumerable<string> selectedBarcodes)
    {
        List<OrderItem> orderItems = new List<OrderItem>();

        foreach (var item in selectedBarcodes)
        {
            string barcode = string.Empty;
            int amount = 1;

            if (item.Contains(Seperator))
            {
                var barcodeParts = item.Split(Seperator);

                barcode = barcodeParts[0];
                amount = int.Parse(barcodeParts[1]);
            }
            else
            {
                barcode = item;
            }

            orderItems.Add(new OrderItem { Barcode = barcode, Amount = amount });
        }

        return orderItems;
    }

    public static IEnumerable<OrderItem> GroupBarcodes(IEnumerable<OrderItem> barcodesAndAmount)
    {
        return barcodesAndAmount.GroupBy(o => o.Barcode)
            .Select(g => new OrderItem { Barcode = g.Key, Amount = g.Sum(o => o.Amount)});
    }
}
